<template>
  <div class="dialog">
    <el-dialog :title="'称重管理'" :visible.sync="showDialog" width="45%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="批次编号:" prop="productionBatchId" class="w50p">
          <el-select v-model="formData.productionBatchId" filterable clearable placeholder="选择批次" @change="batchChange">
            <el-option v-for="(item, index) in batchList" :key="index" :label="`${item.mnecode}_${item.varietyName}`"
              :value="item.productionBatchId" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格:" prop="specificationId" class="w50p">
          <el-select v-model="formData.specificationId" filterable clearable placeholder="请先选择规格">
            <el-option v-for="(item, index) in specificationList" :key="index" :label="item.specificationName"
              :value="item.specificationId" />
          </el-select>
        </el-form-item>
        <el-form-item label="数量：" class="w50p" prop="num">
          <el-input v-model="formData.num" type="number" clearable placeholder="请输入数量">
            <template slot="append">尾</template>
          </el-input>
        </el-form-item>
        <el-form-item label="重量：" class="w50p" prop="weight">
          <el-input v-model="formData.weight" type="number" clearable placeholder="请输入重量">
            <template slot="append">斤</template>
          </el-input>
        </el-form-item>
        <el-form-item label="作业人:" prop="weightStaffName" class="w50p">
          <el-select v-model="formData.weightStaffId" allow-create filterable clearable @change="staffchange">
            <el-option v-for="(item, index) in staffList" :key="index" :label="item.staffName" :value="item.staffId" />
          </el-select>
        </el-form-item>
        <el-form-item label="称重日期：" class="w50p" prop="weightDate">
          <el-date-picker v-model="formData.weightDate" type="date" :picker-options="pickerOptions" placeholder="请选择日期"
            value-format="yyyy-MM-dd" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import WeightRecordApi from "@/api/inputPond/weight-record"
import BatchMangeApi from "@/api/batch-mange"
import SpecificationApi from "@/api/basic-info-manage/specification"
import { dialogMixin } from "@/utils/dialogMixin";
let maxTime = null
export default {
  name: '',
  components: {},
  mixins: [dialogMixin],
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
    staffList: {
      type: [Array],
      default: () => {
        return []
      }
    },
    pondList: {
      type: [Array],
      default: () => {
        return []
      }
    },
    materialList: {
      type: [Array],
      default: () => {
        return []
      }
    },
  },
  data() {
    let checkInt = (rule, value, callback) => {
      if (Number(value) && Number(value) > 0) {
        let str = value + ''
        let valueList = str.split(".")
        if (valueList.length == 1) {
          callback();
        } else if (valueList.length == 2 && valueList[1].length > 2) {
          return callback(new Error("请输入重量，小数最多保留两位！"));
        }
      } else {
        return callback(new Error("请输入大于0的数！"));
      }
    };
    let validatorNumber = (rule, value, callback) => {
      if (Number(value) && Number(value) % 1 == 0) {
        callback();
      } else {
        return callback(new Error("请输入大于0的数！"));
      }
    };
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },

        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      },
      rules: {
        productionBatchId: [
          { required: true, message: "请选择批次编号", trigger: "blur" }
        ],
        specificationId: [
          { required: true, message: "请先选择规格", trigger: "blur" }
        ],
        num: [
          { required: true, message: "请输入数量", trigger: "blur" }, {
            validator: validatorNumber, trigger: ["change", "blur"]
          }
        ],
        weight: [
          { required: true, message: "请输入重量", trigger: "blur" }, {
            validator: checkInt, trigger: ["change", "blur"]
          }
        ],
        weightDate: [
          { required: true, message: "请选择日期", trigger: "blur" }
        ],
        weightStaffId: [
          { required: true, message: "请选择作业人", trigger: "blur" }
        ]
      },
      batchList: [],
      specificationList: [],
      formData: {},
      showDialog: this.show,
      buildDateTime: ''
    };
  },
  computed: {
  },
  watch: {
    show(v) {
      maxTime = null
      this.showDialog = v;
      if (!v) {
        this.$refs['ruleForm'].resetFields()
        console.log('重置表单验证')
        this.buildDateTime = ''
      }
    },
    nowChanceStau(v) {
      if (v === 'add') {
        let staffName = sessionStorage.getItem("staffName")
        let staffId = sessionStorage.getItem("staffId")
        let userList = this.staffList.filter(item => {
          return Number(item.staffId) === Number(staffId)
        })
        this.formData = {
          // weightStaffName: staffId == 1 ? this.staffList[0].staffName : staffName,
          // weightStaffId: staffId == 1 ? this.staffList[0].staffId : Number(staffId),
          weightStaffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
          weightStaffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
          weightDate: new Date()
        }
      }
      if (v === 'edit') {
        this.formData = this.editObject
        setTimeout(() => {
          this.batchChange(this.editObject.productionBatchId)
        }, 100)
      }
    }
  },
  created() {
    maxTime = null
  },
  mounted() {
    this.queryBatch()
    this.querySpecification()
  },
  methods: {
    changeTime(time) {
      let buildDateTime = new Date(this.buildDateTime).getTime(new Date(this.buildDateTime))
      let newtime = new Date(time).getTime(new Date(time))
      if (buildDateTime > newtime) {
        this.formData.weightDate = this.buildDateTime
        this.$message.info('称重时间不得小于批次创建时间' + this.buildDateTime + '！')
      }
    },
    //查询未完成批次
    queryBatch() {
      BatchMangeApi.queryByCondition({ batchStatusList: ['CREATE', 'UN_COMPLETE'] }).then(res => {
        this.batchList = res.data;
        console.log(res.data, '批次')
      })
    },
    batchChange(e) {
      maxTime = ''
      this.formData.weightDate = new Date()
      this.batchList.find(item => {
        if (item.productionBatchId === e) {
          this.querySpecification(item.fishVarietyId)
          this.buildDateTime = item.buildDateTime
          maxTime = new Date(item.buildDateTime)
          // this.formData.weightDate = this.formatDateTimeMHS(maxTime)
        }
      })
    },
    querySpecification(fishVarietyId) {
      SpecificationApi.queryByCondition({ fishVarietyId: fishVarietyId }).then(res => {
        this.specificationList = res.data
      })
    },
    staffchange(id) {
      this.staffList.forEach(item => {
        if (item.staffId == id) {
          this.formData.weightStaffName = item.staffName
        }
      })
      console.log(this.formData)
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            WeightRecordApi.edit(this.formData).then(res => {
              if (res.success === true) {
                this.$message.success("修改成功！");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          } else if (this.nowChanceStau === "add") {
            WeightRecordApi.add(this.formData).then(res => {
              if (res.success === true) {
                this.$message.success("添加成功！");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped></style>
